package com.example.mode.adapter;

import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.mode.R;
import com.example.mode.beam.VideoData;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
    private List<VideoData> videoData;

    //右键生成构造函数
    public VideoAdapter(List<VideoData> videoData) {
        this.videoData = videoData;
    }
    @NotNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
        return new VideoViewHolder(LayoutInflater.from(parent.getContext())
                .inflate(R.layout.videos, parent, false));
    }

    @Override
    public void onBindViewHolder(@NotNull VideoViewHolder holder, int position) {
        holder.setData(videoData.get(position));
    }

    @Override
    public int getItemCount() {
        return videoData.size();
    }

    static class VideoViewHolder extends RecyclerView.ViewHolder {
        VideoView videoView;
        ProgressBar progressBar;
        TextView videoTitle, videoSubTitle;

        public VideoViewHolder(View itemView) {
            super(itemView);
            videoView = itemView.findViewById(R.id.videoView);
            videoTitle = itemView.findViewById(R.id.textViewTitle);
            videoSubTitle = itemView.findViewById(R.id.textViewSubTitle);
            progressBar = itemView.findViewById(R.id.progressBar);
        }

        public void setData(VideoData videoData) {
            videoTitle.setText(videoData.videoTitle);
            videoSubTitle.setText(videoData.videoSubtitle);
            videoView.setVideoPath(videoData.videoURL);
            videoView.setOnPreparedListener(mediaPlayer -> {
                progressBar.setVisibility(View.GONE);
                mediaPlayer.start();
            });
            videoView.setOnCompletionListener(MediaPlayer::start);
        }
    }
}
